// 安全的肉鸽增强系统 - 避免破坏原有功能
class RoguelikeEnhancedSafe {
    constructor() {
        this.runCount = this.loadRunCount();
        this.currentRun = this.initializeCurrentRun();
        this.legacyBonuses = this.loadLegacyBonuses();
        this.unlockedContent = this.loadUnlockedContent();
        
        // 简化的事件系统
        this.eventSystem = new SimpleEventSystem();
        
        // 安全模式标志
        this.safeMode = true;
        
        console.log('🛡️ 安全肉鸽增强系统初始化');
    }
    
    initializeCurrentRun() {
        return {
            startTime: Date.now(),
            upgradesChosen: [],
            eventsEncountered: [],
            weaponsFound: [],
            totalKills: 0,
            totalDamage: 0,
            levelsCompleted: 0,
            runId: this.generateRunId()
        };
    }
    
    // 安全地开始新的游戏轮次
    startNewRun() {
        try {
            this.runCount++;
            this.currentRun = this.initializeCurrentRun();
            
            // 应用遗产奖励
            this.applyLegacyBonuses();
            
            // 重置临时效果
            if (window.roguelikeSystem && window.roguelikeSystem.resetTemporaryEffects) {
                window.roguelikeSystem.resetTemporaryEffects();
            }
            
            this.saveRunData();
            console.log(`🎮 开始第 ${this.runCount} 轮游戏`);
            
        } catch (error) {
            console.error('新轮次开始失败:', error);
        }
    }
    
    // 安全地处理玩家死亡
    handlePlayerDeath() {
        try {
            const runData = this.currentRun;
            const deathRewards = this.calculateDeathRewards(runData);
            
            // 保存部分金币作为遗产
            const coinsToKeep = Math.floor(deathRewards.totalCoins * 0.3);
            if (window.roguelikeSystem && window.roguelikeSystem.addCurrency) {
                window.roguelikeSystem.addCurrency(coinsToKeep);
            }
            
            // 添加遗产奖励
            this.addLegacyBonus(runData);
            
            // 显示死亡总结界面
            this.showDeathSummary(runData, deathRewards);
            
            console.log(`💀 第 ${this.runCount} 轮结束`);
            
        } catch (error) {
            console.error('死亡处理失败:', error);
        }
    }
    
    calculateDeathRewards(runData) {
        try {
            const baseCoins = 50;
            const killBonus = runData.totalKills * 2;
            const levelBonus = runData.levelsCompleted * 25;
            const timeBonus = Math.floor((Date.now() - runData.startTime) / 1000 / 60) * 5;
            
            return {
                totalCoins: baseCoins + killBonus + levelBonus + timeBonus,
                newUnlocks: [],
                legacyPoints: Math.floor(runData.levelsCompleted / 2) + 1
            };
        } catch (error) {
            console.error('死亡奖励计算失败:', error);
            return { totalCoins: 50, newUnlocks: [], legacyPoints: 1 };
        }
    }
    
    addLegacyBonus(runData) {
        try {
            const bonusType = this.selectLegacyBonusType(runData);
            
            if (!this.legacyBonuses[bonusType]) {
                this.legacyBonuses[bonusType] = 0;
            }
            
            this.legacyBonuses[bonusType]++;
            this.saveLegacyBonuses();
            
            console.log(`🏆 获得遗产奖励: ${bonusType} (等级 ${this.legacyBonuses[bonusType]})`);
        } catch (error) {
            console.error('遗产奖励添加失败:', error);
        }
    }
    
    selectLegacyBonusType(runData) {
        const bonusTypes = ['startingHealth', 'startingAmmo', 'startingSpeed', 'luckyStart'];
        
        // 根据游戏表现智能选择
        if (runData.totalKills > 30) return 'combatMastery';
        if (runData.levelsCompleted >= 5) return 'survivalInstinct';
        
        // 默认随机选择
        return bonusTypes[Math.floor(Math.random() * bonusTypes.length)];
    }
    
    // 安全地应用遗产奖励
    applyLegacyBonuses() {
        try {
            Object.entries(this.legacyBonuses).forEach(([bonusType, level]) => {
                if (level > 0) {
                    this.applySpecificLegacyBonus(bonusType, level);
                }
            });
        } catch (error) {
            console.error('遗产奖励应用失败:', error);
        }
    }
    
    applySpecificLegacyBonus(bonusType, level) {
        try {
            switch (bonusType) {
                case 'startingHealth':
                    if (window.player && window.player.maxHealth) {
                        const healthBonus = level * 15;
                        window.player.maxHealth += healthBonus;
                        window.player.health = window.player.maxHealth;
                        console.log(`应用生命奖励: +${healthBonus}`);
                    }
                    break;
                    
                case 'startingAmmo':
                    if (window.player && window.player.currentWeapon) {
                        const ammoBonus = level * 10;
                        window.player.currentWeapon.totalAmmo += ammoBonus;
                        console.log(`应用弹药奖励: +${ammoBonus}`);
                    }
                    break;
                    
                case 'startingSpeed':
                    if (window.player && window.player.speed) {
                        window.player.speed *= (1 + level * 0.05);
                        console.log(`应用速度奖励: +${level * 5}%`);
                    }
                    break;
                    
                case 'luckyStart':
                    this.increasedDropRate = 1 + level * 0.2;
                    console.log(`应用幸运奖励: +${level * 20}% 掉落率`);
                    break;
            }
        } catch (error) {
            console.error(`遗产奖励应用失败 (${bonusType}):`, error);
        }
    }
    
    // 安全地触发随机事件
    triggerRandomEvent() {
        try {
            if (Math.random() < 0.3) { // 30%概率触发事件
                const event = this.eventSystem.generateRandomEvent();
                if (event) {
                    this.showEventInterface(event);
                    this.currentRun.eventsEncountered.push(event.id);
                }
            }
        } catch (error) {
            console.error('随机事件触发失败:', error);
        }
    }
    
    // 简化的事件界面
    showEventInterface(event) {
        try {
            console.log(`🎪 随机事件: ${event.title}`);
            
            // 创建简化的事件通知
            this.showEventNotification(event.title, event.description);
            
            // 自动选择第一个选项（简化处理）
            if (event.choices && event.choices.length > 0) {
                setTimeout(() => {
                    this.executeEventChoice(event, event.choices[0]);
                }, 3000);
            }
            
        } catch (error) {
            console.error('事件界面显示失败:', error);
        }
    }
    
    executeEventChoice(event, choice) {
        try {
            if (choice.effect && typeof choice.effect === 'function') {
                choice.effect();
            }
            
            console.log(`🎲 事件选择: ${event.title} -> ${choice.title}`);
            
        } catch (error) {
            console.error('事件选择执行失败:', error);
        }
    }
    
    // 简化的死亡总结界面
    showDeathSummary(runData, rewards) {
        try {
            const playTime = Math.floor((Date.now() - runData.startTime) / 1000 / 60);
            
            const summaryText = `
💀 游戏结束
第 ${this.runCount} 轮统计:
- 关卡完成: ${runData.levelsCompleted}/10
- 敌人击杀: ${runData.totalKills}
- 游戏时间: ${playTime}分钟
- 保留金币: ${Math.floor(rewards.totalCoins * 0.3)}
            `;
            
            console.log(summaryText);
            
            // 显示简化的通知
            this.showEventNotification('游戏结束', '查看控制台了解详细统计信息');
            
            // 自动重新开始（简化流程）
            setTimeout(() => {
                this.startNewRun();
                if (window.game && window.game.startNewGame) {
                    window.game.startNewGame();
                }
            }, 5000);
            
        } catch (error) {
            console.error('死亡总结显示失败:', error);
        }
    }
    
    // 简化的事件通知
    showEventNotification(title, message, duration = 3000) {
        try {
            const notification = document.createElement('div');
            notification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                z-index: 10000;
                background: rgba(0, 0, 0, 0.8);
                color: white;
                padding: 15px;
                border-radius: 8px;
                border: 2px solid #4CAF50;
                max-width: 300px;
                font-size: 14px;
            `;
            
            notification.innerHTML = `
                <strong>${title}</strong><br>
                ${message}
            `;
            
            document.body.appendChild(notification);
            
            setTimeout(() => {
                if (notification.parentNode) {
                    document.body.removeChild(notification);
                }
            }, duration);
            
        } catch (error) {
            console.error('事件通知显示失败:', error);
            console.log(`通知: ${title} - ${message}`);
        }
    }
    
    // 更新运行统计
    updateRunStats(kills = 0, damage = 0) {
        try {
            this.currentRun.totalKills += kills;
            this.currentRun.totalDamage += damage;
            this.saveRunData();
        } catch (error) {
            console.error('运行统计更新失败:', error);
        }
    }
    
    // 记录关卡完成
    completeLevel(levelNumber) {
        try {
            this.currentRun.levelsCompleted = Math.max(this.currentRun.levelsCompleted, levelNumber);
            this.saveRunData();
            
            console.log(`🏆 完成关卡 ${levelNumber}`);
            
        } catch (error) {
            console.error('关卡完成记录失败:', error);
        }
    }
    
    // 工具方法
    generateRunId() {
        return 'run_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    }
    
    // 数据保存/加载
    saveRunData() {
        try {
            localStorage.setItem('roguelikeEnhancedSafe_currentRun', JSON.stringify(this.currentRun));
            localStorage.setItem('roguelikeEnhancedSafe_runCount', this.runCount.toString());
        } catch (error) {
            console.error('运行数据保存失败:', error);
        }
    }
    
    loadRunCount() {
        try {
            const saved = localStorage.getItem('roguelikeEnhancedSafe_runCount');
            return saved ? parseInt(saved) : 0;
        } catch (error) {
            console.error('运行计数加载失败:', error);
            return 0;
        }
    }
    
    saveLegacyBonuses() {
        try {
            localStorage.setItem('roguelikeEnhancedSafe_legacyBonuses', JSON.stringify(this.legacyBonuses));
        } catch (error) {
            console.error('遗产奖励保存失败:', error);
        }
    }
    
    loadLegacyBonuses() {
        try {
            const saved = localStorage.getItem('roguelikeEnhancedSafe_legacyBonuses');
            return saved ? JSON.parse(saved) : {};
        } catch (error) {
            console.error('遗产奖励加载失败:', error);
            return {};
        }
    }
    
    loadUnlockedContent() {
        try {
            const saved = localStorage.getItem('roguelikeEnhancedSafe_unlockedContent');
            return saved ? JSON.parse(saved) : {
                weapons: ['pistol'],
                upgrades: [],
                events: [],
                achievements: []
            };
        } catch (error) {
            console.error('解锁内容加载失败:', error);
            return { weapons: ['pistol'], upgrades: [], events: [], achievements: [] };
        }
    }
}

// 简化的事件系统
class SimpleEventSystem {
    constructor() {
        this.events = this.createSimpleEvents();
    }
    
    createSimpleEvents() {
        return [
            {
                id: 'healthBonus',
                title: '医疗箱',
                description: '发现了一个医疗箱',
                choices: [{
                    title: '使用',
                    effect: () => {
                        if (window.player) {
                            window.player.health = Math.min(window.player.maxHealth, window.player.health + 50);
                            if (window.player.updateHealthUI) {
                                window.player.updateHealthUI();
                            }
                        }
                    }
                }]
            },
            {
                id: 'ammoBonus',
                title: '弹药补给',
                description: '找到了一些弹药',
                choices: [{
                    title: '收集',
                    effect: () => {
                        if (window.player && window.player.currentWeapon) {
                            window.player.currentWeapon.totalAmmo += 30;
                        }
                    }
                }]
            },
            {
                id: 'coinBonus',
                title: '金币奖励',
                description: '获得了一些金币',
                choices: [{
                    title: '收集',
                    effect: () => {
                        if (window.roguelikeSystem && window.roguelikeSystem.addCurrency) {
                            window.roguelikeSystem.addCurrency(25);
                        }
                    }
                }]
            }
        ];
    }
    
    generateRandomEvent() {
        try {
            return this.events[Math.floor(Math.random() * this.events.length)];
        } catch (error) {
            console.error('随机事件生成失败:', error);
            return null;
        }
    }
}

// 替换原有的肉鸽增强系统
if (window.roguelikeEnhanced) {
    delete window.roguelikeEnhanced;
}

window.roguelikeEnhanced = new RoguelikeEnhancedSafe();

console.log('🛡️ 安全肉鸽增强系统已加载');